package com.ymnet.myretrofit;

import android.content.Context;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.File;

/**
 * Created by ZhangQixiang on 2017/2/16.
 */
public class CacheManager {

    private static CacheManager sCacheManager;
    private        File         sCacheDir;

    public static CacheManager getInstance(Context context) {
        if (sCacheManager == null) {
            sCacheManager = new CacheManager(context);
        }
        return sCacheManager;
    }

    private CacheManager(Context context) {
        sCacheDir = new File(
                Environment.getExternalStorageDirectory(),
                context.getPackageName() + File.separator + "cache"
        );

        if (!sCacheDir.exists()) {
            boolean mkdirsSuccess = sCacheDir.mkdirs();
            Log.d("CacheManager-缓存目录建立: ", mkdirsSuccess + "");
        }

    }

    /**
     * 去缓存文件中读取数据,如果没有该url对应的缓存数据,返回null
     */
    @Nullable
    public String getCacheString(String url) {
        File cacheFile = new File(sCacheDir, MD5Util.getMd5(url));
        return StreamUtil.readFrom(cacheFile);
    }

    public void saveCache(String url, String data) {
        File cacheFile = new File(sCacheDir, MD5Util.getMd5(url));
        StreamUtil.saveString(cacheFile, data);
    }

}
